package regex;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author luoweifei
 * 
 */
public class RegexTestUtil {
	private static Pattern pattern;
	private static Scanner scanner = new Scanner(System.in);
	private static String match;

	public static void main(String[] args) {
		for (int i = 0; true; i++) {
			initPattern();
			Matcher matcher = match();
			printf(matcher);
			relace(matcher);
		}
	}

	private static void initPattern() {
		System.out.print("regex:");
		String regex = scanner.nextLine();
		pattern = Pattern.compile(regex);
		// System.out.println(pattern);
	}

	private static Matcher match() {
		System.out.print("match:");
		match = scanner.nextLine();
		return pattern.matcher(match);
	}

	private static void printf(Matcher matcher) {
		while (matcher.find()) {
			System.out.println(String.format("find:%s(%d,%d)", matcher.group(),
					matcher.start(), matcher.end()));
		}

	}

	private static String relace(Matcher matcher) {
		System.out.print("replace with:");
		String rep = scanner.nextLine();
		if (rep == null)
			return null;
		String rs = matcher.replaceAll(rep);
		System.out.println(rs);
		return rs;
	}
}
